package com.sky.mapper;

import com.github.pagehelper.Page;
import com.sky.dto.GoodsSalesDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Mapper
public interface OrdersMapper {
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into orders(" +
            "number, status, user_id, address_book_id, order_time," +
            " pay_method, pay_status, amount, remark, phone, address, " +
            "user_name, consignee, estimated_delivery_time, " +
            "delivery_status, pack_amount, tableware_number, tableware_status)" +
            "value(#{number},#{status},#{userId},#{addressBookId},#{orderTime}," +
            "#{payMethod},#{payStatus},#{amount},#{remark},#{phone},#{address}," +
            "#{userName},#{consignee},#{estimatedDeliveryTime}," +
            "#{deliveryStatus},#{packAmount},#{tablewareNumber},#{tablewareStatus}) ")
    void insert(Orders orders);
    @Select("select * from orders where number=#{orderNumber}")
    Orders getByNumber(String orderNumber);

    void update(Orders orders);

    Page<Orders> pageQuery(OrdersPageQueryDTO pageQueryDTO);


    @Select("select * from orders where id=#{id};")
    Orders getById(Long id);

    /**
     * 根据状态统计订单数量
     * @param status
     */
    @Select("select count(id) from orders where status = #{status}")
    Integer countStatus(Integer status);

    @Select("select * from orders where status=#{status} and order_time <= #{time};")
    List<Orders> getByStatusAndOrderTime(Integer status, LocalDateTime time);

    // update orders set status=6 ,cancel_time= 当前时间 ,cancel_reason=取消的原因
    // where status = 1 and order_time <= 15min前的时间

    @Update("update orders set status=6 , cancel_reason='超时自动取消',cancel_time=#{now}" +
            " where status=1 and order_time <= #{time}")
    void autoCancelTimeoutOrder(LocalDateTime now, LocalDateTime time);

    // update orders set status=5
    // where status = 4 and order_time <= 1h前的时间
    @Update("update orders set status=5 where status=4 and order_time<=#{time}")
    void autoCompleteDeliveryOrder(LocalDateTime time);

    Double sumByMap(Map<String, Object> map);

    Integer countByMap(Map<String, Object> map);

    List<GoodsSalesDTO> getSalesTop10(LocalDateTime beginTime, LocalDateTime endTime);
}
